package eventbus

import "sync"

type EventBus struct {
	subscribes map[string]EventDataChannel
	lock       sync.RWMutex
}

func NewEventBus() *EventBus {
	return &EventBus{subscribes: make(map[string]EventDataChannel)}
}

func (e *EventBus) Sub(topic string) EventDataChannel {
	e.lock.Lock()
	defer e.lock.Unlock()
	if ec, ok := e.subscribes[topic]; ok {
		return ec
	} else {
		c := make(EventDataChannel)
		e.subscribes[topic] = c
		return c
	}
}

func (e *EventBus) Pub(topic string, data interface{}) {
	e.lock.RLock()
	e.lock.RUnlock()
	if ec, ok := e.subscribes[topic]; ok {
		go func() {
			ec <- &EventData{Data: data}
		}()
	}
}
